package com.luojing.myThread.reentrantlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 独占可重入锁ReentrantLock实例
 * @author luojing
 * @create 2018/08/30 下午3:12
 **/
public class ReentrantLockDemo {

  public static void main(String[] args) {
    ReentrantLock lock = new ReentrantLock();

    Count count = new Count();
    for(int i = 0; i < 100;i++){
      new Worker(count,lock).start();
    }
  }
}

class Count{
  private int count = 0;

  public int getCount() {
    return count;
  }

  public void setCount(int count) {
    this.count = count;
  }
}

class Worker extends Thread{
  private Count count;
  private Lock lock;

  Worker(Count count,Lock lock){
    this.count = count;
    this.lock = lock;
  }

  @Override
  public void run(){
    try {
      System.out.println("Thread:" + Thread.currentThread().getName() + "启动");
      lock.lock();
      System.out.println("Thread:" + Thread.currentThread().getName() + "获取锁");
      Thread.sleep(2000L);
      count.setCount(count.getCount() + 1);
      System.out.println(count.getCount());
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      lock.unlock();
      System.out.println("Thread:" + Thread.currentThread().getName() + "释放锁");
    }
  }
}